package hunter20240524;

public class binarySearchDemo {
    public static void main(String[] args) {
        int[] arr = {12, 23,25, 26,  34};

        System.out.println(binarySearch(arr, 23));
    }

    public static int binarySearch(int[] arr, int number) {
        //1.定义两个变量记录要查找的范围
        int min = 0;
        int max = arr.length - 1;

        //2.利用循环不断去找要查找的数据
        while (true) {
            if (min > max) {
                return -1;
            }
            //3.找到min和max的中间位置
            int mid = (min + max) / 2;
            //4.拿着mid指向的元素跟要查找的元素进行比较
            if (arr[mid] > number) {
                max = mid - 1;
                //number在mid的左边
                //min不变，max=mid-1
            } else if (arr[mid] < number) {
                min = mid + 1;
                //number在mid右边
                //max不变，min=mid+1
            } else {
                //number和mid指向的元素一样
                //找到了
                return mid;
            }
        }


    }
}
